const request = require('../../../utils/request.js');
Page({
  data: {
    img: '',
    username: 'user123',
    nickname: '用户123',
    email: 'user123@example.com',
    phone: '1234567890',
    password:'',
  },
  onLoad(){
    this.getUserData();
  },

  // 头像上传回调
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadAvatar(tempFilePath);
      },
    });
  },
  uploadAvatar(filePath) {
    wx.uploadFile({
      url: 'http://localhost:8080/upload/image',  // 替换成你自己的上传接口地址
      filePath: filePath,
      name: 'file',
      success: (res) => {
        const data = JSON.parse(res.data);
        console.log(data.data);
        this.setData({
          img: data.data  // 假设返回的url字段为头像上传后的地址
        });
      },
      fail: (err) => {
        console.error('头像上传失败', err);
      }
    });
  },

  getUserData(){
    request.post('/index/UserData')
    .then(res=>{
      console.log(res)
      this.setData({
        img : res.data.img,
        username : res.data.username,
        email : res.data.email,
        phone : res.data.phone,
        password:res.data.password,
        nickname  : res.data.nickname
      })
    })
  },

  // 输入框事件处理
  onUsernameInput(event) {
    this.setData({ username: event.detail.value });
  },
  onNicknameInput(event) {
    this.setData({ nickname: event.detail.value });
  },
  onEmailInput(event) {
    this.setData({ email: event.detail.value });
  },
  onPhoneInput(event) {
    this.setData({ phone: event.detail.value });
  },

  // 保存个人信息
  saveProfile() {
    const { username, nickname, email, phone,password,img } = this.data;
    // 实际应用中，可能需要调用接口保存数据
    const param = {
      username,
      nickname,
      email,
      phone,
      password,
      img
    }
    request.post('/index/UserUpdate',param)
    .then(res=>{
      console.log(res);
      if (res.code === 0) {
        wx.switchTab({
          url: '/pages/user/user', 
          success: function () {
            console.log('跳转成功');
          },
          fail: function (err) {
            console.error('跳转失败', err);
          }
        });        
        wx.showToast({
          title: '修改成功',
          icon: 'success',
        });
      } else {
        wx.showToast({
          title: res.msg || '修改失败',
          icon: 'none',
        });
      }
    })
  }
});
